﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using EFERP;
using HRM.DICTIONARY.DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevExpress.Data.Linq;
using DevExpress.Utils;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraGrid.Views.Grid;

namespace HRM.DICTIONARY.UI
{
    public partial class xfrmContract : XtraForm
    {
        private ICommon<hrm_contract> _exeDic;
        private ICommon<hrm_employee> _exeDicEmployee;
        private ICommon<hrm_branch> exebra;
        private ICommon<hrm_department> exedep;
        private ICommon<hrm_group> exegro;

        private hrm_contract _currObj;
        private bool _isChooseRow;
        private List<hrm_employee> _listEmployees;
        private List<hrm_contract> _listContract;

        private DataTable dt;
        private int m_Status = 2;
        private bool m_IsAll = false;
        private Point m_Point;
        private string m_refFiler;
        private hrm_branchEx currBranch;

        public xfrmContract()
        {
            InitializeComponent();
            this.Focus();
        }

        private void xfrmContract_Load(object sender, EventArgs e)
        {
            _exeDic = new Common<hrm_contract>(StaticVariable.ERPEn);
            _exeDicEmployee = new Common<hrm_employee>(StaticVariable.ERPEn);
            exebra = new Common<hrm_branch>(StaticVariable.ERPEn);
            exedep = new Common<hrm_department>(StaticVariable.ERPEn);
            exegro = new Common<hrm_group>(StaticVariable.ERPEn);

            _exeDic.GV = gbList;
            _exeDic.GC = gcList;
            _exeDic.ColIDName = "contractcode";
            _listEmployees = _exeDicEmployee.GetList();

          
            ReloadTreeList(0);
            LoadListEmployee(_listEmployees);
        }

        private void Add()
        {
            xfrmContractAdd frm = new xfrmContractAdd(_exeDic);
            frm.ShowDialog();
            if (_exeDic.myAction == Actions.Insert || _exeDic.myAction == Actions.InsertMultiple)
            {
                _exeDic.myAction = Actions.View;
            }
            Reload(_listContract);
        }

        private void Edit()
        {
            xfrmContractAdd frm = new xfrmContractAdd(_currObj, _exeDic);
            frm.ShowDialog();
            if (_exeDic.myAction == Actions.Update)
            {
                _exeDic.myAction = Actions.View;
                Reload(_listContract);
            }
            _isChooseRow = false;
            DoShowOrHide(_isChooseRow);
        }

        private void Delete()
        {
            bool kq = _exeDic.DeleteOnGridView(_currObj);
            if (kq)
            {
                _isChooseRow = false;
                DoShowOrHide(_isChooseRow); 
            }
            else
            {
                MessageBox.Show(@"Không thể xóa dữ liệu");
            }
        }

        private void Reload(List<hrm_contract> listcontract)
        {
            if (_exeDic != null && _exeDicEmployee != null)
            {
                _exeDic.AddGridControlFromList(listcontract);
                _isChooseRow = false;
                _currObj = null;
                DoShowOrHide(_isChooseRow);
            }
        }

        public void Print()
        {
            if (gbList != null)
            {
                if (gbList.RowCount > 0)
                {
                    gbList.ShowPrintPreview();
                    _isChooseRow = false;
                    _currObj = null;
                    DoShowOrHide(_isChooseRow);
                }
            }
        }

        public void Export()
        {
            if (_exeDic != null)
            {
                _exeDic.AddGridExport(this);
                _isChooseRow = false;
                _currObj = null;
                DoShowOrHide(_isChooseRow);
            }
        }

        private void DoShowOrHide(bool isChoose)
        {
            bbiEdit.Enabled = isChoose;
            bbiDelete.Enabled = isChoose;
        }

        private void LoadListEmployee(List<hrm_employee> listEmployee)
        {
            try
            {
                imgListEmployee.Items.Clear();
                foreach (hrm_employee objEmp in listEmployee)
                {
                    ImageListBoxItem item = new ImageListBoxItem
                    {
                        Value =
                            objEmp.firstname + " " + objEmp.lastname + " (" +
                            objEmp.employeecode + ")",
                        ImageIndex = objEmp.sex == 1 ? 0 : 1,
                    };

                    if (int.Parse(objEmp.status.ToString()) == 3)
                    {
                        item.Value = item.Value + " - Đã nghỉ việc";
                        item.ImageIndex = 2;
                    }
                    this.imgListEmployee.Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Escape:
                    Dispose();
                    return true;

                case Keys.F1:
                    //Help Link Click
                    return true;

                case Keys.F5:
                    this.Reload(_listContract);
                    return true;

                case (Keys.Control | Keys.E):
                    this.Export();
                    return true;

                case (Keys.Control | Keys.F):
                    //Search
                    return true;

                case (Keys.Control | Keys.N):
                    Add();
                    return true;

                case (Keys.Enter):
                    Edit();
                    return true;

                case (Keys.Control | Keys.X):
                    Delete();
                    return true;

                case (Keys.Control | Keys.P):
                    this.Print();
                    return true;

                case (Keys.Alt | Keys.X):
                    Dispose();
                    return true;
            }
            return false;
        }

        #region TreeList Display Organization // Sơ đồ cơ cấu tổ chức
        private void LoadTreeList()
        {
            string m_CompanyName = "NTSC";

            this.dt = new DataTable();
            this.dt.Columns.Add("ID");
            this.dt.Columns.Add("Name");
            this.dt.Columns.Add("ParentID");
            this.dt.Columns.Add("Type");
            this.dt.Columns.Add("FactQuantity");
            this.dt.Columns.Add("Quantity");
            this.dt.Columns.Add("ImageIndex");
            try
            {
                List<hrm_branch> lstBranch = exebra.GetList();
                List<hrm_department> lstDepartment = exedep.GetList();
                List<hrm_group> lstGroup = exegro.GetList();

                //Nhân viên quản lý toàn bộ chi nhánh. (Chùm cuối)
                if (StaticVariable.UserLogin.management == 0)
                {
                    this.dt.Rows.Add(new object[] { "All", m_CompanyName, "NTSC Groups Com.", "Company", 0, 0, 0 });
                    int factQuantity = 0;
                    int quantity = 0;

                    foreach (hrm_branch objbra in lstBranch)
                    {
                        this.dt.Rows.Add(new object[] { objbra.branchcode.ToString(), objbra.branchname.ToString() + this.StringQuantity(objbra), "All", "Branch", int.Parse(objbra.factquantity.ToString()), int.Parse(objbra.quantity.ToString()), 1 });
                        factQuantity += int.Parse(objbra.factquantity.ToString());
                        quantity += int.Parse(objbra.quantity.ToString());

                        //Load All Department with this branchcode
                        var listDep = exedep.Where(n => n.branchcode == objbra.branchcode).ToList();

                        foreach (hrm_department objdep in listDep)
                        {
                            this.dt.Rows.Add(new object[] { objdep.departmentcode.ToString(), objdep.departmentname.ToString() + this.StringQuantity(objdep), objdep.branchcode.ToString(), "Department", int.Parse(objdep.factquantity.ToString()), int.Parse(objdep.quantity.ToString()), 2 });

                            //Load All Group with this departmentcode 
                            var listGro = exegro.DbSet.Where(m => m.departmentcode == objdep.departmentcode).ToList();
                            foreach (hrm_group objgro in listGro)
                            {
                                this.dt.Rows.Add(new object[] { objgro.groupcode.ToString(), objgro.groupname.ToString() + this.StringQuantity(objgro), objgro.departmentcode.ToString(), "Group", int.Parse(objgro.factquantity.ToString()), int.Parse(objgro.quantity.ToString()), 3 });
                            }
                        }
                    }
                    this.dt.Rows[0]["Name"] = this.dt.Rows[0]["Name"].ToString() + this.StringQuantity(factQuantity, quantity);
                    this.dt.Rows[0]["FactQuantity"] = factQuantity;
                    this.dt.Rows[0]["Quantity"] = quantity;
                }
                //Nhân viên đăng nhập trực thuộc chi nhánh.
                else if (StaticVariable.UserLogin.management == 1)
                {
                    var lstBranchLocal = lstBranch.Where(d => d.branchcode == StaticVariable.UserLogin.branchcode).ToList().SingleOrDefault();
                    this.dt.Rows.Add(new object[] { lstBranchLocal.branchcode, lstBranchLocal.branchname + this.StringQuantity(int.Parse(lstBranchLocal.factquantity.ToString()), int.Parse(lstBranchLocal.quantity.ToString())), "", "Branch", lstBranchLocal.factquantity, lstBranchLocal.quantity, 1 });

                    //Lấy phòng ban nhân viên bởi branchcode nhân viên này trực thuộc
                    var lstDepartmentLocal = lstDepartment.Where(i => i.branchcode == lstBranchLocal.branchcode).OrderBy(s => s.departmentcode).ToList();
                    foreach (hrm_department objdep in lstDepartmentLocal)
                    {
                        this.dt.Rows.Add(new object[] { objdep.departmentcode.ToString(), objdep.departmentname.ToString() + this.StringQuantity(objdep), objdep.branchcode, "Department", int.Parse(objdep.factquantity.ToString()), int.Parse(objdep.quantity.ToString()), 2 });

                        var lstGroupLocal = lstGroup.Where(m => m.departmentcode == objdep.departmentcode).OrderBy(e => e.groupcode).ToList();
                        foreach (hrm_group objgro in lstGroupLocal)
                        {
                            this.dt.Rows.Add(new object[] { objgro.groupcode.ToString(), objgro.groupname.ToString() + this.StringQuantity(objgro), objgro.departmentcode.ToString(), "Group", int.Parse(objgro.factquantity.ToString()), int.Parse(objgro.quantity.ToString()), 3 });
                        }
                    }
                }
                else if (StaticVariable.UserLogin.management == 2)
                {
                    var lstDepartmentLocal = lstDepartment.Where(d => d.departmentcode == StaticVariable.UserLogin.departmentcode).ToList().SingleOrDefault();
                    this.dt.Rows.Add(new object[] { lstDepartmentLocal.departmentcode, lstDepartmentLocal.departmentname + this.StringQuantity(int.Parse(lstDepartmentLocal.factquantity.ToString()), int.Parse(lstDepartmentLocal.quantity.ToString())), "", "Department", lstDepartmentLocal.factquantity, lstDepartmentLocal.quantity, 2 });

                    var lstGroupLocal = lstGroup.Where(m => m.departmentcode == lstDepartmentLocal.departmentcode).OrderBy(e => e.groupcode).ToList();
                    foreach (hrm_group objgro in lstGroupLocal)
                    {
                        this.dt.Rows.Add(new object[] { objgro.groupcode.ToString(), objgro.groupname.ToString() + this.StringQuantity(objgro), objgro.departmentcode, "Group", int.Parse(objgro.factquantity.ToString()), int.Parse(objgro.quantity.ToString()), 3 });
                    }
                }
                else
                {
                    var lstGroupLocal = lstGroup.Where(d => d.groupcode == StaticVariable.UserLogin.groupcode).ToList().SingleOrDefault();

                    this.dt.Rows.Add(new object[] { lstGroupLocal.groupcode, lstGroupLocal.groupname + this.StringQuantity(int.Parse(lstGroupLocal.factquantity.ToString()), int.Parse(lstGroupLocal.quantity.ToString())), "", "Group", lstGroupLocal.factquantity, lstGroupLocal.quantity, 3 });
                }
                this.treeStruct.DataSource = this.dt;
                this.treeStruct.ExpandAll();
            }
            catch
            {
            }
        }
        private string StringQuantity(hrm_branch obj)
        {
            if (((this.m_Status == 0) || (this.m_Status == 1)) || (this.m_Status == 3))
            {
                return (" (" + obj.quantity.ToString() + "/" + obj.factquantity.ToString() + ")");
            }
            if (this.m_Status == 2)
            {
                return (" (" + obj.quantity.ToString() + ")");
            }
            int num = int.Parse(obj.factquantity.ToString()) - int.Parse(obj.quantity.ToString());
            return (" (" + num.ToString() + ")");
        }
        private string StringQuantity(hrm_department obj)
        {
            if (((this.m_Status == 0) || (this.m_Status == 1)) || (this.m_Status == 3))
            {
                return (" (" + obj.quantity.ToString() + "/" + obj.factquantity.ToString() + ")");
            }
            if (this.m_Status == 2)
            {
                return (" (" + obj.quantity.ToString() + ")");
            }
            int num = int.Parse(obj.factquantity.ToString()) - int.Parse(obj.quantity.ToString());
            return (" (" + num.ToString() + ")");
        }
        private string StringQuantity(hrm_group obj)
        {
            if (((this.m_Status == 0) || (this.m_Status == 1)) || (this.m_Status == 3))
            {
                return (" (" + obj.quantity.ToString() + "/" + obj.factquantity.ToString() + ")");
            }
            if (this.m_Status == 2)
            {
                return (" (" + obj.quantity.ToString() + ")");
            }
            int num = int.Parse(obj.factquantity.ToString()) - int.Parse(obj.quantity.ToString());
            return (" (" + num.ToString() + ")");
        }
        private string StringQuantity(int FactQuantity, int Quantity)
        {
            if (((this.m_Status == 0) || (this.m_Status == 1)) || (this.m_Status == 3))
            {
                return (" (" + Quantity.ToString() + "/" + FactQuantity.ToString() + ")");
            }
            if (this.m_Status == 2)
            {
                return (" (" + FactQuantity.ToString() + ")");
            }
            int num = Quantity - FactQuantity;
            return (" (" + num.ToString() + ")");
        }
        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            DataRowView dataRecordByNode = (DataRowView)this.treeStruct.GetDataRecordByNode(e.Node);
            this.currBranch = new hrm_branchEx();
            if (e.Node != null)
            {
                if (dataRecordByNode["Type"].ToString() == "Company")
                {
                    currBranch.Level = 0;
                    currBranch.Code = "";
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.todate < DateTime.Today).ToList();
                            break;
                    }
                   
                }
                else if (dataRecordByNode["Type"].ToString() == "Branch")
                {
                    currBranch.branchcode = dataRecordByNode["ID"].ToString();
                    currBranch.Code = dataRecordByNode["ID"].ToString();
                    currBranch.Level = 1;
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.branchcode == currBranch.branchcode).ToList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.branchcode == currBranch.branchcode && s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.branchcode == currBranch.branchcode && s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.branchcode == currBranch.branchcode && s.todate < DateTime.Today).ToList();
                            break;
                    }
                }
                else if (dataRecordByNode["Type"].ToString() == "Department")
                {
                    currBranch.DepartmentCode = dataRecordByNode["ID"].ToString();
                    currBranch.Code = dataRecordByNode["ID"].ToString();
                    currBranch.Level = 2;
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.departmentcode == currBranch.DepartmentCode).ToList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.departmentcode == currBranch.DepartmentCode && s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.departmentcode == currBranch.DepartmentCode && s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.departmentcode == currBranch.DepartmentCode && s.todate < DateTime.Today).ToList();
                            break;
                    }
                }
                else if (dataRecordByNode["Type"].ToString() == "Group")
                {
                    currBranch.GroupCode = dataRecordByNode["ID"].ToString();
                    currBranch.Code = dataRecordByNode["ID"].ToString();
                    currBranch.Level = 3;
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.groupcode == currBranch.GroupCode).ToList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.groupcode == currBranch.GroupCode && s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.groupcode == currBranch.GroupCode && s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.groupcode == currBranch.GroupCode && s.todate < DateTime.Today).ToList();
                            break;
                    }
                }
                else if (dataRecordByNode["Type"].ToString() == "Employee"){
                    currBranch.EmployeeCode = dataRecordByNode["ID"].ToString();
                    currBranch.Code = dataRecordByNode["ID"].ToString();
                    currBranch.Level = 4;
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.employeecode == currBranch.EmployeeCode).ToList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.employeecode == currBranch.EmployeeCode && s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.employeecode == currBranch.EmployeeCode && s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.employeecode == currBranch.EmployeeCode && s.todate < DateTime.Today).ToList();
                            break;
                    }
                }
            }
            this.treeStruct.SetFocusedNode(e.Node);
            
            Reload(_listContract);
        }
        private void treeList1_GetSelectImage(object sender, DevExpress.XtraTreeList.GetSelectImageEventArgs e)
        {
            DataRowView dataRecordByNode = (DataRowView)this.treeStruct.GetDataRecordByNode(e.Node);
            e.NodeImageIndex = int.Parse(dataRecordByNode["ImageIndex"].ToString());
        }
        //private void treeList1_MouseDown(object sender, MouseEventArgs e)
        //{
        //    this.m_Point = new Point(e.X, e.Y);
        //    if (e.Button == MouseButtons.Right)
        //    {
        //        this.ShowMenu(this.treeStruct.CalcHitInfo(this.m_Point), this.treeStruct.PointToScreen(this.m_Point));
        //    }
        //}
        public void LoadAllData()
        {
            this.m_IsAll = true;
            this.m_Status = 2;
            this.LoadTreeList();
        }
        public void LoadAllData(int Status)
        {
            this.m_IsAll = true;
            this.m_Status = Status;
            this.LoadTreeList();
        }
        public void LoadData()
        {
            this.m_IsAll = false;
            this.m_Status = 2;
            this.LoadTreeList();
        }
        public void LoadData(int Status)
        {
            this.m_IsAll = false;
            this.m_Status = Status;
            this.LoadTreeList();
        }
        private void ReloadTreeList(int m_Status)
        {
            if (this.m_IsAll)
            {
                this.LoadAllData();
            }
            else
            {
                this.LoadData(m_Status);
            }
        }
        public void SelectNodeByLevelCode(int Level, string Code)
        {
            foreach (TreeListNode node in this.treeStruct.Nodes)
            {
                if ((int.Parse(node.GetValue("ImageIndex").ToString()) == Level) && (node.GetValue("ID").ToString() == Code))
                {
                    this.treeStruct.SetFocusedNode(node);
                    break;
                }
                foreach (TreeListNode node2 in node.Nodes)
                {
                    if ((int.Parse(node2.GetValue("ImageIndex").ToString()) == Level) && (node2.GetValue("ID").ToString() == Code))
                    {
                        this.treeStruct.SetFocusedNode(node2);
                        break;
                    }
                    foreach (TreeListNode node3 in node2.Nodes)
                    {
                        if ((int.Parse(node3.GetValue("ImageIndex").ToString()) == Level) && (node3.GetValue("ID").ToString() == Code))
                        {
                            this.treeStruct.SetFocusedNode(node3);
                            break;
                        }
                        foreach (TreeListNode node4 in node3.Nodes)
                        {
                            if ((int.Parse(node4.GetValue("ImageIndex").ToString()) == Level) && (node4.GetValue("ID").ToString() == Code))
                            {
                                this.treeStruct.SetFocusedNode(node4);
                                break;
                            }
                        }
                    }
                }
            }
        }
        public void SetFocusedNode(string code)
        {
            this.treeStruct.SetFocusedNode(this.treeStruct.FindNodeByFieldValue("ID", code));
        }
        //private void ShowMenu(TreeListHitInfo hi, Point point)
        //{
        //    DataRowView dataRecordByNode = (DataRowView)this.treeStruct.GetDataRecordByNode(hi.Node);
        //    this.treeStruct.SetFocusedNode(hi.Node);
        //    if (hi.Node != null)
        //    {
        //        if (dataRecordByNode["Type"].ToString() == "Company")
        //        {
        //            this.ppCompany.ShowPopup(point);
        //        }
        //        else if (dataRecordByNode["Type"].ToString() == "Branch")
        //        {
        //            this.ppBranch.ShowPopup(point);
        //        }
        //        else if (dataRecordByNode["Type"].ToString() == "Department")
        //        {
        //            this.ppDepartment.ShowPopup(point);
        //        }
        //        else if (dataRecordByNode["Type"].ToString() == "Group")
        //        {
        //            this.ppGroup.ShowPopup(point);
        //        }
        //        else if (dataRecordByNode["Type"].ToString() == "Employee")
        //        {
        //            this.ppEmployee.ShowPopup(point);
        //        }
        //    }
        //}
        //private void bbiAddBranch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    xucBranchAdd frmAdd = new xucBranchAdd(exebra);
        //    DialogResult res = frmAdd.ShowDialog();
        //    if (res == DialogResult.OK)
        //        ReloadTreeList(0);
        //}
        //private void bbiBranchDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    if (XtraMessageBox.Show("Bạn có muốn xóa không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
        //    {
        //        string str = "";
        //        string branchCode = null;
        //        bool KQ = false;

        //        branchCode = currBranch.branchcode;
        //        if (branchCode != null)
        //        {
        //            ////SYS_LOG.Insert("Danh S\x00e1ch Chi Nh\x00e1nh", "Xo\x00e1", branchCode.ToString());
        //            SetWaitDialogCaption("Đang xóa...");

        //            //exeEmp                            //int Level, string Code, int Status, DateTime DayFirstMonth, DateTime DayEndMonth
        //            using (var trans = StaticVariable.ERPEn.Database.BeginTransaction())
        //            {
        //                try
        //                {
        //                    var lstEmpinBranch = _exeDicEmployee.DbSet.Where(d => d.branchcode == branchCode).ToList();
        //                    var lstEmpinDepartment = exedep.DbSet.Where(i => i.hrm_branch.branchcode == branchCode).ToList();
        //                    foreach (hrm_employee objEmp in lstEmpinBranch)
        //                    {
        //                        SetWaitDialogCaption("Đang xóa nhân viên..." + objEmp.firstname.ToString() + " " + objEmp.lastname.ToString());
        //                        KQ = _exeDicEmployee.Delete(objEmp);
        //                        if (!KQ)
        //                            continue;
        //                    }
        //                    foreach (hrm_department objDep in lstEmpinDepartment)
        //                    {
        //                        var lstEmpinGroup = exegro.DbSet.Where(s => s.departmentcode == objDep.departmentcode).ToList();
        //                        foreach (hrm_group objGro in lstEmpinGroup)
        //                        {
        //                            SetWaitDialogCaption("Đang xóa tổ, nhóm..." + objGro.groupname.ToString());
        //                            KQ = exegro.Delete(objGro);
        //                            if (!KQ)
        //                                continue;
        //                        }
        //                        SetWaitDialogCaption("Đang xóa bộ phận..." + objDep.departmentname.ToString());
        //                        KQ = exedep.Delete(objDep);
        //                        if (!KQ)
        //                            continue;
        //                    }
        //                    SetWaitDialogCaption("Đang xóa chi nhánh này...");
        //                    KQ = exebra.Delete(branchCode);
        //                    StaticVariable.Save();
        //                    trans.Commit();
        //                    if (KQ)
        //                    {
        //                        treeStruct.Nodes.Remove(treeStruct.FocusedNode);
        //                        ReloadTreeList(0);
        //                    }
        //                    else
        //                    {
        //                        MessageBox.Show("Thông tin không được xóa\n" + str, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    if (trans != null)
        //                        trans.Rollback();
        //                    MessageBox.Show("Thông tin không được xóa\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        //                }
        //                DoHide();
        //            }
        //        }
        //    }
        //}
        //private void bbiBranchEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    string branchCode = null;

        //    branchCode = currBranch.branchcode;
        //    if (branchCode != null)
        //    {
        //        SetWaitDialogCaption("Đang kiểm tra dữ liệu....");
        //        hrm_branch item = exebra.DbSet.Find(branchCode);
        //        if (item == null)
        //        {
        //            this.DoHide();
        //            XtraMessageBox.Show("Dữ liệu không tồn tại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //        }
        //        else
        //        {
        //            this.DoHide();
        //            xucBranchAdd frm = new xucBranchAdd(item, exebra);
        //            DialogResult res = frm.ShowDialog();
        //            if (res == DialogResult.OK)
        //                ReloadTreeList(0);
        //        }
        //    }
        //}

        //private void bbiAddDepartment_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    xucDepartmentAdd frmAdd = new xucDepartmentAdd(exedep);
        //    DialogResult res = frmAdd.ShowDialog();
        //    if (res == System.Windows.Forms.DialogResult.OK)
        //        ReloadTreeList(0);
        //}
        //private void bbiDepartmentEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    string departmentCode = null;

        //    departmentCode = currBranch.DepartmentCode;
        //    if (departmentCode != null)
        //    {
        //        SetWaitDialogCaption("Đang kiểm tra dữ liệu....");
        //        hrm_department item = exedep.DbSet.Find(departmentCode);
        //        if (item == null)
        //        {
        //            this.DoHide();
        //            XtraMessageBox.Show("Dữ liệu không tồn tại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //        }
        //        else
        //        {
        //            this.DoHide();
        //            xucDepartmentAdd frmadd = new xucDepartmentAdd(item, exedep);
        //            DialogResult res = frmadd.ShowDialog();
        //            if (res == System.Windows.Forms.DialogResult.OK)
        //                ReloadTreeList(0);
        //        }
        //    }
        //}
        //private void bbiDepartmentDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    if (XtraMessageBox.Show("Bạn có muốn xóa không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
        //    {
        //        bool KQ = false;
        //        string departmentCode = null;
        //        departmentCode = currBranch.DepartmentCode;
        //        if (departmentCode != null)
        //        {
        //            //SYS_LOG.Insert("Danh S\x00e1ch Ph\x00f2ng Ban", "Xo\x00e1", departmentCode.ToString());
        //            SetWaitDialogCaption("Đang xóa...");
        //            using (var trans = StaticVariable.ERPEn.Database.BeginTransaction())
        //            {
        //                try
        //                {
        //                    var lstEmpinDepartment = _exeDicEmployee.DbSet.Where(d => d.departmentcode == departmentCode).ToList();
        //                    foreach (hrm_employee objEmp in lstEmpinDepartment)
        //                    {
        //                        SetWaitDialogCaption("Đang xóa nhân viên..." + objEmp.firstname.ToString() + " " + objEmp.lastname.ToString());
        //                        KQ = _exeDicEmployee.Delete(objEmp);
        //                        if (!KQ)
        //                            continue;
        //                    }
        //                    var lstGroinDepartment = exegro.DbSet.Where(i => i.departmentcode == departmentCode).ToList();
        //                    foreach (hrm_group objGro in lstGroinDepartment)
        //                    {
        //                        SetWaitDialogCaption("Đang xóa tổ nhóm..." + objGro.groupname.ToString());
        //                        KQ = _exeDicEmployee.Delete(objGro);
        //                        if (!KQ)
        //                            continue;
        //                    }
        //                    SetWaitDialogCaption("Đang xóa bộ phận này...");
        //                    KQ = exedep.Delete(departmentCode);
        //                    StaticVariable.Save();
        //                    trans.Commit();
        //                    if (KQ)
        //                    {
        //                        treeStruct.Nodes.Remove(treeStruct.FocusedNode);
        //                        ReloadTreeList(0);
        //                    }
        //                    else
        //                    {
        //                        MessageBox.Show("Thông tin không được xóa\n", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    if (trans != null)
        //                        trans.Rollback();
        //                    MessageBox.Show("Thông tin không được xóa\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        //                }
        //                DoHide();
        //            }
        //        }
        //    }
        //}

        //private void bbiAddGroup_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    xucGroupAdd frmAdd = new xucGroupAdd(exegro);
        //    DialogResult res = frmAdd.ShowDialog();
        //    if (res == DialogResult.OK)
        //        ReloadTreeList(0);
        //}
        //private void bbiGroupEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    string GroupCode = null;

        //    GroupCode = currBranch.GroupCode;
        //    if (GroupCode != null)
        //    {
        //        SetWaitDialogCaption("Đang kiểm tra dữ liệu....");
        //        hrm_group item = exegro.DbSet.Find(GroupCode);//        if (item == null)
        //        {
        //            this.DoHide();
        //            XtraMessageBox.Show("Dữ liệu không tồn tại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //        }
        //        else
        //        {
        //            this.DoHide();
        //            xucGroupAdd frmadd = new xucGroupAdd(item, exegro);
        //            DialogResult res = frmadd.ShowDialog();
        //            if (res == System.Windows.Forms.DialogResult.OK)
        //                ReloadTreeList(0);
        //        }
        //    }
        //}
        //private void bbiGroupDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    bool KQ = false;
        //    string groupCode = null;
        //    groupCode = currBranch.GroupCode;
        //    if (groupCode != null)
        //    {
        //        //SYS_LOG.Insert("Danh S\x00e1ch Tổ Nh\x00f3m", "Xo\x00e1", groupCode.ToString());
        //        SetWaitDialogCaption("Đang xóa...");
        //        using (var trans = StaticVariable.ERPEn.Database.BeginTransaction())
        //        {
        //            try
        //            {
        //                var lstEmpinGroup = _exeDicEmployee.DbSet.Where(d => d.groupcode == groupCode).ToList();
        //                foreach (hrm_employee objEmp in lstEmpinGroup)
        //                {
        //                    SetWaitDialogCaption("Đang xóa..." + objEmp.firstname.ToString() + " " + objEmp.lastname.ToString());
        //                    KQ = _exeDicEmployee.Delete(objEmp);
        //                    if (!KQ) continue;
        //                }
        //                SetWaitDialogCaption("Đang xóa tổ nhóm này..,");
        //                KQ = exegro.Delete(groupCode);

        //                if (KQ)
        //                {
        //                    treeStruct.Nodes.Remove(treeStruct.FocusedNode);
        //                    ReloadTreeList(0);
        //                }
        //                else
        //                {
        //                    MessageBox.Show("Thông tin không được xóa\n", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                if (trans != null)
        //                    trans.Rollback();
        //                MessageBox.Show("Thông tin không được xóa\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        //            }
        //            DoHide();
        //        }
        //    }
        //}

        //private void bbiReload_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    ReloadTreeList(0);
        //}
        //private void bbiTransferBranch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    //Get Current list employee by branchcode
        //    //hrm_employee.GetListCurrentNow(1, this.cls.BranchCode, -1) //int Level, string Code, int Status
        //    string branchcode = currBranch.branchcode;
        //    var lstEmpinBranch = _exeDicEmployee.DbSet.Where(d => d.branchcode == branchcode).OrderBy(k => k.employeecode).ToList();
        //    xfrmTransfer transfer = new xfrmTransfer(lstEmpinBranch, exebra, exedep, exegro, _exeDicEmployee);
        //    DialogResult res = transfer.ShowDialog();
        //    if (res == System.Windows.Forms.DialogResult.OK)
        //        ReloadTreeList(0);
        //}
        //private void bbiTransferDepartment_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    string departmentcode = currBranch.DepartmentCode;
        //    var lstEmpinDepartment = _exeDicEmployee.DbSet.Where(d => d.departmentcode == departmentcode).OrderBy(k => k.employeecode).ToList();
        //    xfrmTransfer transfer = new xfrmTransfer(lstEmpinDepartment, exebra, exedep, exegro, _exeDicEmployee);
        //    DialogResult res = transfer.ShowDialog();
        //    if (res == System.Windows.Forms.DialogResult.OK)
        //        ReloadTreeList(0);
        //}
        //private void bbiTransferGroup_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    string groupcode = currBranch.GroupCode;
        //    var lstEmpinGroup = _exeDicEmployee.DbSet.Where(d => d.groupcode == groupcode).OrderBy(k => k.employeecode).ToList();
        //    xfrmTransfer transfer = new xfrmTransfer(lstEmpinGroup, exebra, exedep, exegro, _exeDicEmployee);
        //    DialogResult res = transfer.ShowDialog();
        //    if (res == System.Windows.Forms.DialogResult.OK)
        //        ReloadTreeList(0);
        //}

        #endregion TreeList Display Organization // Sơ đồ cơ cấu tổ chức

        private WaitDialogForm dlg = null;
        public void SetWaitDialogCaption(string fCaption)
        {
            if (this.dlg != null)
            {
                this.dlg.Caption = fCaption;
            }
            else
            {
                CreateWaitDialog();
                if (this.dlg != null){
                    this.dlg.Caption = fCaption;
                }
            }
        }
        public void CreateWaitDialog()
        {
            this.dlg = new WaitDialogForm("Đang trong quá trình thao tác...", "Vui lòng đợi trong giây lát...");
        }
        protected virtual void DoHide()
        {
            base.OnLoad(EventArgs.Empty);
            if (this.dlg != null)
            {
                this.dlg.FormClosing += new FormClosingEventHandler(this.dlg_FormClosing);
                this.dlg.Close();
            }
        }
        private void dlg_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.dlg.Dispose();
            this.dlg = null;
        }

        #region Events

        private void bbiAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Add();
        }

        private void bbiEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit();
        }

        private void bbiDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Delete();
        }

        private void bbiRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Reload(_listContract);
        }

        private void bbiPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Print();
        }

        private void bbiExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Export();
        }

        private void bbiClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Dispose();
        }

        private void gbList_Click(object sender, EventArgs e)
        {
            _currObj = _exeDic.gbList_Click(sender, e);
            if (_currObj == null)
            {
                MessageBox.Show("Vui lòng chọn dòng trên bảng tính");
            }
            else
            {
                _isChooseRow = true;
                DoShowOrHide(_isChooseRow);
            }
        }

        private void gbList_DoubleClick(object sender, EventArgs e)
        {
            _currObj = _exeDic.gbList_Click(sender, e);
            if (_currObj == null)
            {
                MessageBox.Show("Vui lòng chọn dòng trên bảng tính");
            }
            else
            {
                Edit();
            }
        }

        private void imgListEmployee_Click(object sender, EventArgs e)
        {
            try
            {
                ImageListBoxItem item = (ImageListBoxItem)imgListEmployee.SelectedItem;
                string maTenNv = item.Value.ToString();
                int indexMaNv = maTenNv.IndexOf("(", StringComparison.Ordinal);
                string maNv = maTenNv.Substring(indexMaNv + 1);
                maNv = maNv.Replace(")", "");
                _listContract = _exeDic.GetList().Where(s => s.employeecode == maNv).ToList();
                Reload(_listContract);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void imgListEmployee_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                this.imgListEmployee.Items.RemoveAt(this.imgListEmployee.SelectedIndex);
            }
        }

        private void btSearch_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            List<hrm_employee> listemployee = _listEmployees.Where(s => s.employeecode == btSearch.Text || (s.firstname + " " + s.lastname).Contains(btSearch.Text)).ToList();
            LoadListEmployee(listemployee);
        }

        private void btSearch_EditValueChanged(object sender, EventArgs e)
        {
            List<hrm_employee> listemployee = _listEmployees.Where(s => s.employeecode == btSearch.Text || (s.firstname + " " + s.lastname).Contains(btSearch.Text)).ToList();
            LoadListEmployee(listemployee);
            if (this.btSearch.Text == "")
            {
                this.btSearch.EditValue = null;
            }
        }

        private void gbList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            this.m_Point = new Point(e.X, e.Y);
            if (e.Button == MouseButtons.Right)
            {
                this.popupMenu1.ShowPopup(m_Point);
            }
        }

       

        private void repFilter_EditValueChanging(object sender, ChangingEventArgs e)
        {
            this.m_refFiler = e.NewValue.ToString();
        }
        #endregion Events

        private void repFilter_EditValueChanged(object sender, EventArgs e)
        {
            switch (currBranch.Level)
            {
                case 0:
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.todate < DateTime.Today).ToList();
                            break;
                    }
                    break;

                case 1:
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.branchcode == currBranch.branchcode).ToList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.branchcode == currBranch.branchcode && s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.branchcode == currBranch.branchcode && s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.branchcode == currBranch.branchcode && s.todate < DateTime.Today).ToList();
                            break;
                    }
                    break;

                case 2:
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.departmentcode == currBranch.DepartmentCode).ToList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.departmentcode == currBranch.DepartmentCode && s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.departmentcode == currBranch.DepartmentCode && s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.departmentcode == currBranch.DepartmentCode && s.todate < DateTime.Today).ToList();
                            break;
                    }
                    break;

                default:
                    switch (m_refFiler)
                    {
                        case "0":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.employeecode == currBranch.EmployeeCode).ToList();
                            break;
                        case "1":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.employeecode == currBranch.EmployeeCode && s.fromdate <= DateTime.Today && s.todate >= DateTime.Today).ToList();
                            break;
                        case "2":
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.employeecode == currBranch.EmployeeCode && s.todate <= DateTime.Today.AddDays(10)).ToList();
                            break;
                        default:
                            _listContract = _exeDic.GetList().Where(s => s.hrm_employee.employeecode == currBranch.EmployeeCode && s.todate < DateTime.Today).ToList();
                            break;
                    }
                    break;
            }
            Reload(_listContract);
        }

      

       

       

    }
}